<template>
  <div class="paramConfig">
    <DFPageList ref="dfPageListRef" :page-options="pageOptions">
      <template #materialPicture>
        <n-upload
          :default-file-list="previewFileList"
          list-type="image-card"
          :custom-request="customRequest"
          accept=".png,.jpg,.jpeg,.pdf"
        />
      </template>
    </DFPageList>
    <UnitOptionsDialog
      ref="unitOptionsDialogRef"
      :chooseItem="chooseItem"
      :imgList="imgList"
      :machine="machine"
      :parameterUnitList="parameterUnitList"
      :routeName="'material'"
    />

    <ChooseMachine
      ref="chooseMachineRef"
      :machineList="machineList"
      :routeName="'material'"
      :machine="null"
      @setChooseMachineCodeFn="setChooseMachineCodeFn"
    />
  </div>
</template>

<script lang="ts" setup name="Material">
  import lang from './lang';
  import {
    addMaterial,
    delMaterial,
    pageMaterial,
    updateMaterial,
    exportMaterial,
  } from '@/api/base/material';
  import { listCustom } from '@/api/base/custom';
  import { fileUpload } from '@/api/common';
  import { useMixins } from '@/hooks/useMixins';
  import { generateRandomValue } from '@/utils/index';
  import { storage } from '@render/utils/Storage';
  import { listKnife } from '@/api/base/knife';
  import UnitOptionsDialog from '@/views/permission/wip/productionCenter/components/UnitOptionsDialog.vue';
  import ChooseMachine from '@/views/permission/wip/productionCenter/components/ChooseMachine.vue';
  import { convertPdfToImageFn } from '@render/utils/pdfToImg';
  import { getParameterUnitByMaterialVersion } from '@render/api/base/material';
  import { listMachine } from '@render/api/base/machine';
  // import productionCenterLang from '@/views/permission/wip/productionCenter/lang/zh';

  const unitOptionsDialogRef = ref(null);

  const chooseMachineRef = ref(null);

  const {
    loadLangFn,
    getDictDataListFn,
    // t
  } = useMixins();

  const dfPageListRef: any = ref(null);

  loadLangFn(lang);

  // loadLangFn(productionCenterLang,'productionCenter');

  const cartonTypeNameList = ref([]);

  const corrugatedTypeNameList = ref([]);

  const outModeNameList = ref([]);

  const previewFileList = ref([]);

  const customList = ref([]);

  const knifeList = ref([]);

  const machineList: any = ref([]);

  // const perfectPressList = ref([
  //   { label: t('common.button.no'), value: 0 },
  //   { label: t('common.button.yes'), value: 1 },
  // ]);

  // function handlePreview() {}

  async function customRequest({ file, onFinish, onError }) {
    const form = new FormData();
    form.append('file', file.file as string | Blob);

    const res = await fileUpload(form);

    const { code, data } = res;

    if (code === 200) {
      onFinish();

      previewFileList.value.push({
        status: 'finished',
        url: data.url,
      });

      // console.log(previewFileList.value)
    } else {
      onError();
    }

    // console.log(res);
  }

  async function initDictData() {
    const res = await Promise.all([
      getDictDataListFn('corrugated_type'),
      getDictDataListFn('carton_type'),
      getDictDataListFn('out_mode'),
      listCustom(),
      listKnife(),
      listMachine(),
    ]);

    const [list1, list2, list3, list4, list5, list6] = res;

    machineList.value = list6?.data || [];

    cartonTypeNameList.value = list2;

    corrugatedTypeNameList.value = list1;

    outModeNameList.value = list3;

    customList.value = list4.data || [];

    knifeList.value = list5.data || [];
  }

  initDictData();

  const chooseItem = ref(null);

  const imgList = ref([]);

  const machine = ref(null);

  const parameterUnitList = ref([]);

  const setChooseMachineCodeFn = async (val, fn) => {
    machine.value = machineList.value.find((item) => item.machineCode === val.machineCode);

    const { materialPicture, materialCode, version } = chooseItem.value;

    const res = await getParameterUnitByMaterialVersion({
      materialCode,
      version,
      machineCode: val.machineCode,
    });

    parameterUnitList.value = res.data || [];

    if (materialPicture) {
      const materialPictureList = [];

      const pictureList = materialPicture.split(',');

      for (let i = 0; i < pictureList.length; i++) {
        const item = pictureList[i];

        const fileExtension = item.substring(item.lastIndexOf('.') + 1).toLowerCase();

        if (fileExtension === 'pdf') {
          const list: any = await convertPdfToImageFn(
            `http://${storage.get('host')}:3000/file/${item}`
          );

          materialPictureList.push(...list);
        } else {
          materialPictureList.push(`http://${storage.get('host')}:3000/file/${item}`);
        }
      }

      imgList.value = materialPictureList;
    } else {
      imgList.value = [];
    }

    fn && fn();

    nextTick(() => {
      unitOptionsDialogRef.value?.openModalFn();
    });
  };

  const pageOptions = {
    searchForm: {
      formSchemas: [
        {
          label: 'materialName',
        },
        {
          label: 'materialCode',
        },
      ],
    },
    table: {
      hasSelection: true,
      columns: [
        {
          width: 120,
          label: 'materialName',
        },
        {
          width: 120,
          label: 'materialCode',
        },
        {
          width: 120,
          label: 'version',
        },
        {
          width: 120,
          label: 'remark',
          common: true,
        },
      ],
      action: {
        columns: [
          {
            label: 'options',
            click: async (row) => {
              chooseItem.value = row;

              chooseMachineRef.value?.openModalFn();
            },
          },
          {
            label: 'check',
          },
          {
            label: 'copy',
          },
          {
            label: 'delete',
          },
        ],
      },
      operaColumn: [
        {
          label: 'add',
        },
        {
          label: 'export',
        },
      ],
      requestFn: pageMaterial,
      delRequestFn: delMaterial,
      exportRequestFn: exportMaterial,
    },
    modalFormDialog: {
      formSchemas: [
        {
          label: 'materialName',
          required: true,
        },
        {
          label: 'materialCode',
          editDialogDisabled: true,
          required: true,
        },
        {
          label: 'version',
          required: true,
        },
        {
          label: 'customName',
          prop: 'customCode',
          checkProp: 'customName',
          component: 'NSelect',
          options: customList,
          componentProps: {
            labelField: 'customName',
            valueField: 'customCode',
            filterable: true,
            tag: true,
            'on-create': (label: string) => {
              const customCode = generateRandomValue(16);
              return { customShort: label, customCode, customName: label };
            },
            onUpdateValue: (_v: string, option: any, updateFormModelFn: any) => {
              if (updateFormModelFn && option) {
                const { customShort, customName, customCode } = option;

                const data: any = {
                  customShort,
                  customName,
                  customCode,
                };

                typeof updateFormModelFn === 'function' && updateFormModelFn(data);
              } else {
                typeof updateFormModelFn === 'function' &&
                  updateFormModelFn({
                    customShort: null,
                    customName: null,
                    customCode: null,
                  });
              }
            },
          },
        },
        {
          label: 'customerNo',
        },
        {
          label: 'cartonTypeName',
          prop: 'cartonTypeCode',
          checkProp: 'cartonTypeName',
          required: true,
          component: 'NSelect',
          options: cartonTypeNameList,
        },
        {
          label: 'corrugatedTypeName',
          prop: 'corrugatedTypeCode',
          checkProp: 'corrugatedTypeName',
          component: 'NSelect',
          required: true,
          options: corrugatedTypeNameList,
          componentProps: {
            onUpdateValue(_v: string, option: any, updateFormModelFn: any, formModel: any) {
              if (formModel && option.extend1) {
                typeof updateFormModelFn === 'function' &&
                  updateFormModelFn({
                    paperThickness: Number(option.extend1),
                  });
              }
            },
          },
        },
        {
          label: 'paperThickness',
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'outModeName',
          prop: 'outModeCode',
          checkProp: 'outModeName',
          required: true,
          component: 'NSelect',
          options: outModeNameList,
        },
        {
          label: 'materialLength',
          required: true,
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'materialWidth',
          required: true,
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'materialHeight',
          required: true,
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'paperLength',
          required: true,
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'paperWidth',
          required: true,
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'templateNum',
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'nail',
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'pileNum',
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'lid',
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'materialPrice',
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
        },
        {
          label: 'paperPrice',
          requiredRulesType: 'number',
          component: 'NInputNumber',
          componentProps: {
            maxlength: 50,
            min: 0,
            precision: 0,
            clearable: true,
            showButton: false,
          },
          span: 3,
        },
        {
          label: 'knifeName',
          prop: 'knifeCode',
          checkProp: 'knifeName',
          component: 'NSelect',
          options: knifeList,
          componentProps: {
            labelField: 'knifeName',
            valueField: 'knifeCode',
            filterable: true,
            tag: true,
            'on-create': (label: string) => {
              const knifeCode = generateRandomValue(16);
              return { knifeCode, knifeName: label };
            },
            onUpdateValue(v: string, option: any, updateFormModelFn: any) {
              if (typeof updateFormModelFn === 'function') {
                if (v) {
                  const { knifeCode, knifeName } = option;

                  updateFormModelFn({
                    knifeName,
                    knifeCode,
                  });
                } else {
                  updateFormModelFn({
                    knifeName: null,
                    knifeCode: null,
                  });
                }
              }
            },
          },
          span: 3,
        },
        // {
        //   label: 'perfectPress',
        //   checkPropFn: ({ perfectPress }) => {
        //     return (
        //       perfectPressList.value.find((item: any) => item.value === perfectPress)?.label || '-'
        //     );
        //   },
        //   component: 'NSelect',
        //   defaultValue: 0,
        //   options: perfectPressList,
        //   span: 3
        // },
        {
          label: 'materialPicture',
          slot: 'materialPicture',
          slotValueName: 'materialPicture',
          giProps: { span: 4 },
          span: 3,
        },
        {
          label: 'remark',
          common: true,
          type: 'textarea',
          giProps: { span: 4 },
          span: 3,
        },
      ],
      cols: 2,
      addDataFn: addMaterial,
      updateDataFn: updateMaterial,
      afterDialogSubmitFn: initDictData,
      setDialogDataFn: async (data, type) => {
        previewFileList.value = [];
        if (type === 'add') {
          const newData: any = {};

          newData.cartonTypeCode = cartonTypeNameList.value[0].value;

          newData.corrugatedTypeCode = corrugatedTypeNameList.value[0].value;

          newData.paperThickness = corrugatedTypeNameList.value[0]?.extend1
            ? Number(corrugatedTypeNameList.value[0].extend1)
            : undefined;

          newData.version = 'V1.0';

          newData.outModeCode = outModeNameList.value[0].value;

          return newData;
        }

        if (type === 'copy') {
          delete data.id;
        }

        if (data && data.materialPicture)
          previewFileList.value = data.materialPicture.split(',').map((item) => ({
            url: `http://${storage.get('host')}:3000/file/${item}`,
            status: 'finished',
          }));

        // console.log(previewFileList.value)

        return data;
      },
      setDialogSubmitDataFn: (data) => {
        const { corrugatedTypeCode, cartonTypeCode, outModeCode } = data;

        data.materialPicture = previewFileList.value.map((item) => item.url).join(',') || '';

        data.corrugatedTypeName = corrugatedTypeCode
          ? corrugatedTypeNameList.value.find((item) => item.value === corrugatedTypeCode)?.label ||
            ''
          : '';

        data.cartonTypeName = cartonTypeCode
          ? cartonTypeNameList.value.find((item) => item.value === cartonTypeCode)?.label || ''
          : '';

        data.outModeName = outModeCode
          ? outModeNameList.value.find((item) => item.value === outModeCode)?.label || ''
          : '';

        return data;
      },
    },
  };

  // nextTick(() => {
  //   dfPageListRef.value && dfPageListRef.value.openModalFn();
  // });
</script>
